package com.smarttest.portal.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smarttest.common.beans.JsonDataResult;
import com.smarttest.common.util.HttpClientUtil;
import com.smarttest.portal.mapper.RuleParamMapper;
import com.smarttest.portal.pojo.RuleParam;
import com.smarttest.portal.pojo.RuleParamExample;
import com.smarttest.portal.pojo.RuleParamExample.Criteria;
import com.smarttest.portal.service.RuleParamService;


@Service
public class RuleParamServiceImpl implements RuleParamService{
    @Autowired
	RuleParamMapper ruleParamMapper;
    private static Set<String> ruleIndexies = null;
    

	@Override
	public JsonDataResult getRuleParamByRuleType(String ruleType) {
		RuleParamExample example = new RuleParamExample();
		Criteria criteria = example.createCriteria();
		criteria.andRuleTypeEqualTo(ruleType);
		// TODO Auto-generated method stub
		List<RuleParam> list = ruleParamMapper.selectByExampleWithBLOBs(example);
		//判断是否查询到结果
		if (list != null && list.size() > 0) {
			return JsonDataResult.ok(list.get(0));
		}
		return JsonDataResult.ok();
	}

	@Override
	public JsonDataResult insertRuleParam(RuleParam ruleParam) {
		// TODO Auto-generated method stub
		//补全pojo
		ruleParam.setCreated(new Date());
		ruleParam.setUpdated(new Date());
		//插入到规则表
		ruleParamMapper.insert(ruleParam);
		return JsonDataResult.ok();
	}
	
	
	@PostConstruct
	public void afterConstruct(){
//		Timer timer = new Timer(); 
//		timer.schedule(new ReadFromRemoteTask(), 1000, 20000000);
	}
	
	
	private Set<String> buildResults(String rawRules){
		JSONObject JSON = (JSONObject) JSONArray.parse(rawRules);
		JSONObject indices = JSON.getJSONObject("indices");
		Set<String> set = indices.keySet();
		return set;
	}
	
	
	class ReadFromRemoteTask extends TimerTask{
		public void run(){
			String SEARCH_BASE_URL = "http://172.16.18.53:9200/_stats";
			Map<String, String> param = new HashMap<>();
			String json = HttpClientUtil.doGet(SEARCH_BASE_URL, param);
			if(json!=null&&json.length()>0){
			ruleIndexies = buildResults(json);
			}
		}
	}

	@Override
	public Set<String> getRuleIndexes() {
		// TODO Auto-generated method stub
		return ruleIndexies;
	}

	@Override
	public JsonDataResult getRuleTypes() {
		// TODO Auto-generated method stub
		RuleParamExample example = new RuleParamExample();
		example.setDistinct(true);
		// TODO Auto-generated method stub
		List<String> list = ruleParamMapper.selectRuleType(example);
		//判断是否查询到结果
		if (list != null && list.size() > 0) {
			return JsonDataResult.ok(list);
		}
		return JsonDataResult.ok();
	}
}
